"""
订单管理接口
"""

from flask import request, current_app
from app.api.v1 import api_v1
from app.models.order import Order
from app.models.venue import Venue
from app.models.user import User
from app import db
from app.utils.decorators import admin_required
from app.utils.response import success_response, error_response
from flasgger import swag_from
from sqlalchemy import func, extract
from datetime import datetime, date


@api_v1.route('/admin/orders', methods=['GET'])
@admin_required
@swag_from({
    "tags": ["订单管理"],
    "summary": "获取订单列表",
    "description": "管理员获取订单列表，支持分页、搜索和筛选\n\n**🔐 需要管理员Token认证**",
    "security": [{"Bearer": []}],
    "parameters": [
        {"name": "page", "in": "query", "type": "integer", "default": 1, "description": "页码，从1开始"},
        {"name": "per_page", "in": "query", "type": "integer", "default": 10, "description": "每页数量，默认10条"},
        {"name": "status", "in": "query", "type": "integer", "enum": [0, 1, 2, 3, 4], "description": "订单状态筛选：0=待支付，1=已支付，2=已取消，3=已完成，4=已退款"},
        {"name": "venue_id", "in": "query", "type": "integer", "description": "场馆ID筛选"},
        {"name": "user_id", "in": "query", "type": "integer", "description": "用户ID筛选"},
        {"name": "start_date", "in": "query", "type": "string", "format": "date", "description": "开始日期筛选，格式：YYYY-MM-DD"},
        {"name": "end_date", "in": "query", "type": "string", "format": "date", "description": "结束日期筛选，格式：YYYY-MM-DD"},
        {"name": "search", "in": "query", "type": "string", "description": "搜索关键词，支持订单号搜索"}
    ],
    "responses": {
                "200": {
            "description": "获取订单列表成功",
            "schema": {
                "type": "object",
                "properties": {
                    "code": {"type": "integer", "example": 200},
                    "message": {"type": "string", "example": "获取订单列表成功"},
                    "data": {
                        "type": "object",
                        "properties": {
                            "total": {"type": "integer", "description": "总记录数", "example": 18},
                            "pages": {"type": "integer", "description": "总页数", "example": 2},
                            "page": {"type": "integer", "description": "当前页码", "example": 1},
                            "per_page": {"type": "integer", "description": "每页数量", "example": 10},
                            "orders": {
                                "type": "array",
                                "description": "订单列表",
                                "items": {
                                    "type": "object",
                                    "properties": {
                                        "id": {"type": "integer", "description": "订单ID", "example": 1},
                                        "order_no": {"type": "string", "description": "订单号", "example": "ORD202406200001"},
                                        "user_id": {"type": "integer", "description": "用户ID", "example": 2},
                                        "user_name": {"type": "string", "description": "用户姓名", "example": "张三"},
                                        "venue_id": {"type": "integer", "description": "场馆ID", "example": 1},
                                        "venue_name": {"type": "string", "description": "场馆名称", "example": "篮球场A"},
                                        "reservation_date": {"type": "string", "description": "预约日期", "example": "2024-06-21"},
                                        "time_slot": {"type": "string", "description": "时间段", "example": "09:00-11:00"},
                                        "amount": {"type": "number", "description": "订单金额", "example": 100.0},
                                        "status": {"type": "integer", "description": "订单状态", "example": 0},
                                        "status_text": {"type": "string", "description": "状态描述", "example": "未支付"},
                                        "created_at": {"type": "string", "description": "创建时间", "example": "2024-06-20 10:30:00"},
                                        "updated_at": {"type": "string", "description": "更新时间", "example": "2024-06-20 10:30:00"}
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        "401": {"description": "未授权访问"},
        "500": {"description": "服务器内部错误"}
    }
})
def get_orders():
    """管理员获取订单列表"""
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        status = request.args.get('status', type=int)
        venue_id = request.args.get('venue_id', type=int)
        user_id = request.args.get('user_id', type=int)
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        search = request.args.get('search')
        
        # 构建基础查询
        query = Order.query
        
        # 筛选条件
        if status is not None:
            query = query.filter(Order.status == status)
        
        if venue_id:
            query = query.filter(Order.venue_id == venue_id)
            
        if user_id:
            query = query.filter(Order.user_id == user_id)
        
        if start_date:
            try:
                start_date_obj = datetime.strptime(start_date, '%Y-%m-%d').date()
                query = query.filter(Order.reservation_date >= start_date_obj)
            except ValueError:
                pass
                
        if end_date:
            try:
                end_date_obj = datetime.strptime(end_date, '%Y-%m-%d').date()
                query = query.filter(Order.reservation_date <= end_date_obj)
            except ValueError:
                pass
        
        if search:
            query = query.filter(Order.order_no.contains(search))
        
        # 按创建时间降序排列
        query = query.order_by(Order.created_at.desc())
        
        # 分页查询
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        orders_data = []
        for order in pagination.items:
            order_dict = order.to_dict()
            
            # 添加场馆信息
            if order.venue:
                order_dict['venue_name'] = order.venue.name
            else:
                order_dict['venue_name'] = '未知场馆'
            
            # 添加用户信息
            if order.user:
                order_dict['user_name'] = order.user.name
            else:
                order_dict['user_name'] = '未知用户'
            
            # 格式化时间字段
            if order.created_at:
                order_dict['created_at'] = str(order.created_at)
            if order.updated_at:
                order_dict['updated_at'] = str(order.updated_at)
            if order.reservation_date:
                order_dict['reservation_date'] = str(order.reservation_date)
            
            orders_data.append(order_dict)
        
        return success_response({
            'total': pagination.total,
            'pages': pagination.pages,
            'page': page,
            'per_page': per_page,
            'orders': orders_data
        }, '获取订单列表成功')
        
    except Exception as e:
        current_app.logger.error(f"获取订单列表异常: {str(e)}")
        return error_response('服务器错误', 500)


@api_v1.route('/admin/orders/<int:order_id>', methods=['GET'])
@admin_required
@swag_from({
    'tags': ['订单管理'],
    'summary': '获取订单详情',
    'description': '🔐 需要管理员Token认证 - 获取指定订单的详细信息',
    'security': [{'Bearer': []}],
    'parameters': [{'name': 'order_id', 'in': 'path', 'type': 'integer', 'required': True, 'description': '订单ID'}],
    'responses': {200: {
            "description": "获取订单详情成功",
            "schema": {
                "type": "object",
                "properties": {
                    "code": {"type": "integer", "example": 200},
                    "message": {"type": "string", "example": "获取订单详情成功"},
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {"type": "integer", "description": "订单ID", "example": 1},
                            "order_no": {"type": "string", "description": "订单号", "example": "ORD202406200001"},
                            "user_id": {"type": "integer", "description": "用户ID", "example": 2},
                            "venue_id": {"type": "integer", "description": "场馆ID", "example": 1},
                            "venue_name": {"type": "string", "description": "场馆名称", "example": "篮球场A"},
                            "user_name": {"type": "string", "description": "用户姓名", "example": "张三"},
                            "reservation_date": {"type": "string", "description": "预约日期", "example": "2024-06-21"},
                            "time_slot": {"type": "string", "description": "时间段", "example": "09:00-11:00"},
                            "amount": {"type": "number", "description": "订单金额", "example": 100.0},
                            "status": {"type": "integer", "description": "订单状态", "example": 0},
                            "remark": {"type": "string", "description": "订单备注", "example": "团队活动"},
                            "created_at": {"type": "string", "description": "创建时间", "example": "2024-06-20 10:30:00"},
                            "paid_at": {"type": "string", "description": "支付时间", "example": "2024-06-20 10:35:00"}
                        }
                    }
                }
            }
        }, 404: {'description': '订单不存在'}, 401: {'description': '未授权访问'}, 500: {'description': '服务器内部错误'}}
})
def admin_get_order_detail(order_id):
    """获取订单详情"""
    try:
        order = Order.query.get(order_id)
        if not order:
            return error_response('订单不存在', 404)
        
        order_data = order.to_dict(with_venue=True, with_user=True, with_activity=True)
        return success_response(order_data, '获取订单详情成功')
        
    except Exception as e:
        current_app.logger.error(f"获取订单详情异常: {str(e)}")
        return error_response('服务器错误', 500)


@api_v1.route('/admin/orders/statistics', methods=['GET'])
@admin_required
@swag_from({
    'tags': ['订单管理'],
    'summary': '获取订单统计',
    'description': '🔐 需要管理员Token认证 - 获取订单统计数据，包括状态分布、收入统计、趋势分析',
    'security': [{'Bearer': []}],
    'parameters': [
        {'name': 'start_date', 'in': 'query', 'type': 'string', 'format': 'date', 'description': '统计开始日期，格式：YYYY-MM-DD'},
        {'name': 'end_date', 'in': 'query', 'type': 'string', 'format': 'date', 'description': '统计结束日期，格式：YYYY-MM-DD'}
    ],
    'responses': {
        200: {
            'description': '获取成功',
            'schema': {
                'type': 'object',
                'properties': {
                    'code': {'type': 'integer', 'example': 200},
                    'message': {'type': 'string', 'example': '获取成功'},
                    'data': {
                        'type': 'object',
                        'description': '返回的数据'
                    }
                }
            }
        },
        401: {'description': '未授权访问'},
        500: {'description': '服务器内部错误'}
    }
})
def get_order_statistics():
    """获取订单统计信息"""
    try:
        # 获取查询参数
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        
        # 构建基础查询
        base_query = Order.query
        
        # 按日期范围筛选
        if start_date:
            try:
                start_date_obj = datetime.strptime(start_date, '%Y-%m-%d').date()
                base_query = base_query.filter(Order.reservation_date >= start_date_obj)
            except ValueError:
                pass
                
        if end_date:
            try:
                end_date_obj = datetime.strptime(end_date, '%Y-%m-%d').date()
                base_query = base_query.filter(Order.reservation_date <= end_date_obj)
            except ValueError:
                pass
        
        # 订单状态统计
        status_stats = []
        for status in [0, 1, 2, 3, 4]:
            count = base_query.filter(Order.status == status).count()
            status_name = {
                0: '未支付',
                1: '已支付', 
                2: '已取消',
                3: '已完成',
                4: '已退款'
            }.get(status, '未知')
            
            status_stats.append({
                'status': status,
                'status_name': status_name,
                'count': count
            })
        
        # 收入统计（已支付和已完成的订单）
        total_revenue = base_query.filter(Order.status.in_([1, 3])).with_entities(
            func.sum(Order.amount)
        ).scalar() or 0
        
        # 今日订单统计
        today = date.today()
        today_orders = Order.query.filter(
            func.date(Order.created_at) == today
        ).count()
        
        return success_response({
            'status_statistics': status_stats,
            'total_revenue': float(total_revenue),
            'today_orders': today_orders
        }, '获取统计信息成功')
        
    except Exception as e:
        current_app.logger.error(f"获取订单统计异常: {str(e)}")
        return error_response('服务器错误', 500)


@api_v1.route('/admin/orders/export', methods=['GET'])
@admin_required
@swag_from({
    'tags': ['订单管理'],
    'summary': '导出订单数据',
    'description': '🔐 需要管理员Token认证 - 导出订单数据，支持多种筛选条件',
    'security': [{'Bearer': []}],
    'parameters': [
        {'name': 'status', 'in': 'query', 'type': 'integer', 'enum': [0, 1, 2, 3, 4], 'description': '订单状态筛选'},
        {'name': 'start_date', 'in': 'query', 'type': 'string', 'format': 'date', 'description': '开始日期，格式：YYYY-MM-DD'},
        {'name': 'end_date', 'in': 'query', 'type': 'string', 'format': 'date', 'description': '结束日期，格式：YYYY-MM-DD'},
        {'name': 'venue_id', 'in': 'query', 'type': 'integer', 'description': '场馆ID筛选'}
    ],
    'responses': {
        200: {'description': '导出成功'},
        401: {'description': '未授权访问'},
        500: {'description': '服务器内部错误'}
    }
})
def export_orders():
    """导出订单数据"""
    try:
        # 获取查询参数
        status = request.args.get('status', type=int)
        venue_id = request.args.get('venue_id', type=int)
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        
        # 构建查询
        query = Order.query
        
        if status is not None:
            query = query.filter(Order.status == status)
            
        if venue_id:
            query = query.filter(Order.venue_id == venue_id)
            
        if start_date:
            try:
                start_date_obj = datetime.strptime(start_date, '%Y-%m-%d').date()
                query = query.filter(Order.reservation_date >= start_date_obj)
            except ValueError:
                pass
                
        if end_date:
            try:
                end_date_obj = datetime.strptime(end_date, '%Y-%m-%d').date()
                query = query.filter(Order.reservation_date <= end_date_obj)
            except ValueError:
                pass
        
        # 获取所有订单
        orders = query.order_by(Order.created_at.desc()).all()
        
        # 构建导出数据
        export_data = []
        for order in orders:
            order_dict = {
                'id': order.id,
                'order_no': order.order_no,
                'user_name': order.user.name if order.user else '未知用户',
                'venue_name': order.venue.name if order.venue else '未知场馆',
                'amount': float(order.amount) if order.amount else 0,
                'status': order.status,
                'status_text': {0: '未支付', 1: '已支付', 2: '已取消', 3: '已完成', 4: '已退款'}.get(order.status, '未知'),
                'reservation_date': str(order.reservation_date) if order.reservation_date else None,
                'created_at': str(order.created_at) if order.created_at else None
            }
            export_data.append(order_dict)
        
        return success_response({
            'total': len(export_data),
            'export_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'orders': export_data
        }, '导出数据获取成功')
        
    except Exception as e:
        current_app.logger.error(f"导出订单数据异常: {str(e)}")
        return error_response('服务器错误', 500)


@api_v1.route('/admin/orders/simple', methods=['GET'])
@admin_required
@swag_from({
    "tags": ["订单管理"],
    "summary": "获取订单列表（简化版）",
    "description": "管理员获取订单列表的简化版接口，返回基本的订单信息\n\n**🔐 需要管理员Token认证**",
    "security": [{"Bearer": []}],
    "parameters": [
        {"name": "page", "in": "query", "type": "integer", "default": 1, "description": "页码，从1开始"},
        {"name": "per_page", "in": "query", "type": "integer", "default": 10, "description": "每页数量，默认10条"},
        {"name": "status", "in": "query", "type": "integer", "enum": [0, 1, 2, 3, 4], "description": "订单状态筛选：0=待支付，1=已支付，2=已取消，3=已完成，4=已退款"},
        {"name": "venue_id", "in": "query", "type": "integer", "description": "场馆ID筛选"},
        {"name": "user_id", "in": "query", "type": "integer", "description": "用户ID筛选"},
        {"name": "start_date", "in": "query", "type": "string", "format": "date", "description": "开始日期筛选，格式：YYYY-MM-DD"},
        {"name": "end_date", "in": "query", "type": "string", "format": "date", "description": "结束日期筛选，格式：YYYY-MM-DD"},
        {"name": "search", "in": "query", "type": "string", "description": "搜索关键词，支持订单号搜索"}
    ],
    "responses": {
        "200": {
            "description": "获取订单列表成功",
            "schema": {
                "type": "object",
                "properties": {
                    "code": {"type": "integer", "example": 200},
                    "message": {"type": "string", "example": "获取订单列表成功"},
                    "data": {
                        "type": "object",
                        "properties": {
                            "total": {"type": "integer", "description": "总记录数", "example": 18},
                            "pages": {"type": "integer", "description": "总页数", "example": 2},
                            "page": {"type": "integer", "description": "当前页码", "example": 1},
                            "per_page": {"type": "integer", "description": "每页数量", "example": 10},
                            "orders": {
                                "type": "array",
                                "description": "订单列表",
                                "items": {
                                    "type": "object",
                                    "properties": {
                                        "id": {"type": "integer", "description": "订单ID", "example": 1},
                                        "order_no": {"type": "string", "description": "订单号", "example": "ORD202406200001"},
                                        "user_id": {"type": "integer", "description": "用户ID", "example": 2},
                                        "venue_id": {"type": "integer", "description": "场馆ID", "example": 1},
                                        "reservation_date": {"type": "string", "description": "预约日期", "example": "2024-06-21"},
                                        "start_time": {"type": "string", "description": "开始时间", "example": "09:00"},
                                        "end_time": {"type": "string", "description": "结束时间", "example": "11:00"},
                                        "amount": {"type": "number", "description": "订单金额", "example": 100.0},
                                        "status": {"type": "integer", "description": "订单状态", "example": 0},
                                        "status_text": {"type": "string", "description": "状态描述", "example": "未支付"},
                                        "created_at": {"type": "string", "description": "创建时间", "example": "2024-06-20 10:30:00"},
                                        "user": {
                                            "type": "object", 
                                            "description": "用户信息",
                                            "properties": {
                                                "id": {"type": "integer", "description": "用户ID", "example": 2},
                                                "name": {"type": "string", "description": "用户姓名", "example": "张三"},
                                                "phone": {"type": "string", "description": "联系电话", "example": "13800000000"}
                                            }
                                        },
                                        "venue": {
                                            "type": "object", 
                                            "description": "场馆信息",
                                            "properties": {
                                                "id": {"type": "integer", "description": "场馆ID", "example": 1},
                                                "name": {"type": "string", "description": "场馆名称", "example": "篮球场A"},
                                                "location": {"type": "string", "description": "场馆位置", "example": "A区"},
                                                "address": {"type": "string", "description": "场馆地址", "example": "北京市朝阳区"}
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        "401": {"description": "未授权访问"},
        "500": {"description": "服务器内部错误"}
    }
})
def get_orders_simple():
    """管理员获取订单列表（简化版）"""
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        status = request.args.get('status', type=int)
        venue_id = request.args.get('venue_id', type=int)
        user_id = request.args.get('user_id', type=int)
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        search = request.args.get('search')
        
        current_app.logger.info(f"简化订单列表查询参数: page={page}, per_page={per_page}, status={status}")
        
        # 使用原生SQL查询避免时间字段序列化问题
        where_conditions = []
        params = {}
        
        # 按状态筛选
        if status is not None:
            where_conditions.append("o.status = :status")
            params['status'] = status
            
        # 按场馆筛选
        if venue_id:
            where_conditions.append("o.venue_id = :venue_id")
            params['venue_id'] = venue_id
            
        # 按用户筛选
        if user_id:
            where_conditions.append("o.user_id = :user_id")
            params['user_id'] = user_id
            
        # 按日期范围筛选
        if start_date:
            try:
                datetime.strptime(start_date, '%Y-%m-%d')
                where_conditions.append("o.reservation_date >= :start_date")
                params['start_date'] = start_date
            except ValueError:
                pass
                
        if end_date:
            try:
                datetime.strptime(end_date, '%Y-%m-%d')
                where_conditions.append("o.reservation_date <= :end_date")
                params['end_date'] = end_date
            except ValueError:
                pass
        
        # 搜索功能
        if search:
            where_conditions.append("o.order_no LIKE :search")
            params['search'] = f'%{search}%'
        
        # 构建WHERE子句
        where_clause = " WHERE " + " AND ".join(where_conditions) if where_conditions else ""
        
        # 查询总数
        count_sql = f"SELECT COUNT(*) as total FROM orders o {where_clause}"
        count_result = db.session.execute(db.text(count_sql), params).scalar()
        total = count_result if count_result else 0
        
        # 计算偏移量
        offset = (page - 1) * per_page
        
        # 查询订单列表
        list_sql = f"""
        SELECT 
            o.id, o.order_no, o.status, o.amount,
            o.created_at, o.reservation_date, 
            o.start_time, o.end_time, o.user_id, o.venue_id, o.activity_id,
            v.name as venue_name,
            v.location as venue_location,
            v.address as venue_address,
            u.nickname as user_name,
            u.phone as user_phone,
            a.title as activity_title
        FROM orders o
        LEFT JOIN venues v ON o.venue_id = v.id
        LEFT JOIN users u ON o.user_id = u.id
        LEFT JOIN activities a ON o.activity_id = a.id
        {where_clause}
        ORDER BY o.id DESC
        LIMIT :per_page OFFSET :offset
        """
        
        # 添加分页参数
        params['per_page'] = per_page
        params['offset'] = offset
        
        # 执行查询
        list_result = db.session.execute(db.text(list_sql), params)
        orders_data = []
        
        status_map = {0: '未支付', 1: '已支付', 2: '已取消', 3: '已完成', 4: '已退款'}
        
        for row in list_result:
            orders_data.append({
                'id': row.id,
                'order_no': row.order_no,
                'user_id': row.user_id,
                'venue_id': row.venue_id,
                'activity_id': row.activity_id,
                'activity_title': row.activity_title,
                'status': row.status,
                'status_text': status_map.get(row.status, '未知'),
                'amount': float(row.amount) if row.amount else 0,
                'reservation_date': str(row.reservation_date) if row.reservation_date else None,
                'start_time': str(row.start_time) if row.start_time else None,
                'end_time': str(row.end_time) if row.end_time else None,
                'created_at': str(row.created_at) if row.created_at else None,
                # 嵌套的用户信息对象
                'user': {
                    'id': row.user_id,
                    'name': row.user_name or '未知用户',
                    'phone': row.user_phone or '-'
                },
                # 嵌套的场馆信息对象
                'venue': {
                    'id': row.venue_id,
                    'name': row.venue_name or '未知场馆',
                    'location': row.venue_location or '-',
                    'address': row.venue_address or '-'
                }
            })
        
        # 计算总页数
        pages = (total + per_page - 1) // per_page
        
        current_app.logger.info(f"简化订单列表查询结果: total={total}, pages={pages}, 当前页数据条数={len(orders_data)}")
        
        return success_response({
            'total': total,
            'pages': pages,
            'page': page,
            'per_page': per_page,
            'orders': orders_data
        }, '获取订单列表成功')
        
    except Exception as e:
        current_app.logger.error(f"获取简化订单列表异常: {str(e)}")
        import traceback
        current_app.logger.error(f"错误堆栈: {traceback.format_exc()}")
        return error_response('服务器错误', 500)


@api_v1.route('/admin/orders/<int:order_id>/payment', methods=['POST'])
@admin_required
@swag_from({
    "tags": ["订单管理"],
    "summary": "为订单生成支付二维码（增强版）",
    "description": "管理员为指定订单生成微信支付二维码，支持防重复支付、动态配置\n\n**🔐 需要管理员Token认证**",
    "security": [{"Bearer": []}],
    "parameters": [
        {"name": "order_id", "in": "path", "type": "integer", "required": True, "description": "订单ID"},
        {
            "name": "body",
            "in": "body",
            "schema": {
                "type": "object",
                "properties": {
                    "description": {"type": "string", "description": "支付描述", "example": "场馆预约费用"},
                    "expire_minutes": {"type": "integer", "description": "支付过期时间(分钟)", "default": 30, "example": 30}
                }
            }
        }
    ],
    "responses": {
        "200": {
            "description": "支付二维码生成成功",
            "schema": {
                "type": "object",
                "properties": {
                    "code": {"type": "integer", "example": 200},
                    "message": {"type": "string", "example": "支付二维码生成成功"},
                    "data": {
                        "type": "object",
                        "properties": {
                            "payment_id": {"type": "integer", "description": "支付ID", "example": 1},
                            "payment_no": {"type": "string", "description": "支付单号", "example": "PAY20250121001"},
                            "qr_code": {"type": "string", "description": "支付二维码URL", "example": "weixin://wxpay/bizpayurl?pr=xxx"},
                            "amount": {"type": "number", "description": "支付金额", "example": 100.0},
                            "expire_time": {"type": "string", "description": "过期时间", "example": "2025-01-21 15:30:00"}
                        }
                    }
                }
            }
        },
        "400": {"description": "请求参数错误"},
        "401": {"description": "未授权访问"},
        "404": {"description": "订单不存在"},
        "500": {"description": "服务器内部错误"}
    }
})
def generate_payment_qrcode(order_id):
    """为订单生成支付二维码（增强版）"""
    try:
        from app.utils.wechat_pay_enhanced import WeChatPayEnhanced
        
        # 获取请求参数
        data = request.get_json() or {}
        description = data.get('description')
        expire_minutes = data.get('expire_minutes', 30)
        
        # 验证参数
        if expire_minutes <= 0 or expire_minutes > 120:
            return error_response('支付过期时间必须在1-120分钟之间', 400)
        
        # 检查订单是否存在
        order = Order.query.get(order_id)
        if not order:
            return error_response('订单不存在', 404)
        
        # 检查是否必须关联活动
        if not order.activity_id:
            return error_response('订单必须关联活动才能支付', 400)
        
        # 验证活动和金额规则
        activity = order.activity
        if activity:
            # 检查活动状态
            if activity.status != 'open':
                return error_response('关联的活动已关闭，无法支付', 400)
            
            # 检查活动费用与订单金额是否匹配
            if not activity.is_free and activity.fee != order.amount:
                return error_response('订单金额与活动费用不匹配', 400)
            
            # 如果是免费活动，不需要支付
            if activity.is_free:
                return error_response('该活动为免费活动，无需支付', 400)
        
        # 初始化增强版微信支付服务
        try:
            wechat_pay = WeChatPayEnhanced()
        except ValueError as e:
            return error_response(f'微信支付配置错误: {str(e)}', 500)
        
        # 生成支付订单
        try:
            result = wechat_pay.generate_payment_order(
                order_id=order_id,
                description=description,
                expire_minutes=expire_minutes
            )
            
            current_app.logger.info(f"支付二维码生成成功: {result['payment_no']}")
            
            return success_response(result, '支付二维码生成成功')
            
        except ValueError as e:
            return error_response(str(e), 400)
        except Exception as e:
            current_app.logger.error(f"生成支付订单失败: {str(e)}")
            return error_response('生成支付订单失败', 500)
            
    except Exception as e:
        current_app.logger.error(f"生成支付二维码异常: {str(e)}")
        return error_response('服务器错误', 500)


@api_v1.route('/admin/payments', methods=['GET'])
@admin_required
@swag_from({
    "tags": ["支付管理"],
    "summary": "获取支付记录列表",
    "description": "管理员获取支付记录列表，支持分页和筛选\n\n**🔐 需要管理员Token认证**",
    "security": [{"Bearer": []}],
    "parameters": [
        {"name": "page", "in": "query", "type": "integer", "default": 1, "description": "页码"},
        {"name": "per_page", "in": "query", "type": "integer", "default": 10, "description": "每页数量"},
        {"name": "status", "in": "query", "type": "integer", "enum": [0, 1, 2, 3], "description": "支付状态：0=未支付，1=支付成功，2=支付失败，3=已退款"},
        {"name": "payment_method", "in": "query", "type": "string", "description": "支付方式"},
        {"name": "start_date", "in": "query", "type": "string", "format": "date", "description": "开始日期"},
        {"name": "end_date", "in": "query", "type": "string", "format": "date", "description": "结束日期"},
        {"name": "search", "in": "query", "type": "string", "description": "搜索关键词（支付单号、订单号）"}
    ],
    "responses": {
        "200": {
            "description": "获取成功",
            "schema": {
                "type": "object",
                "properties": {
                    "code": {"type": "integer", "example": 200},
                    "message": {"type": "string", "example": "获取支付记录成功"},
                    "data": {
                        "type": "object",
                        "properties": {
                            "total": {"type": "integer", "description": "总记录数"},
                            "pages": {"type": "integer", "description": "总页数"},
                            "page": {"type": "integer", "description": "当前页"},
                            "per_page": {"type": "integer", "description": "每页数量"},
                            "payments": {
                                "type": "array",
                                "items": {
                                    "type": "object",
                                    "properties": {
                                        "id": {"type": "integer", "description": "支付ID"},
                                        "payment_no": {"type": "string", "description": "支付单号"},
                                        "order_no": {"type": "string", "description": "订单号"},
                                        "amount": {"type": "number", "description": "支付金额"},
                                        "status": {"type": "integer", "description": "支付状态"},
                                        "status_text": {"type": "string", "description": "状态描述"},
                                        "payment_method": {"type": "string", "description": "支付方式"},
                                        "paid_at": {"type": "string", "description": "支付时间"},
                                        "created_at": {"type": "string", "description": "创建时间"}
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        "401": {"description": "未授权访问"},
        "500": {"description": "服务器内部错误"}
    }
})
def get_payments():
    """获取支付记录列表"""
    try:
        from app.models.payment import Payment
        
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        status = request.args.get('status', type=int)
        payment_method = request.args.get('payment_method')
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        search = request.args.get('search')
        
        # 使用原生SQL查询
        where_conditions = []
        params = {}
        
        if status is not None:
            where_conditions.append("p.status = :status")
            params['status'] = status
            
        if payment_method:
            where_conditions.append("p.payment_method = :payment_method")
            params['payment_method'] = payment_method
            
        if start_date:
            try:
                datetime.strptime(start_date, '%Y-%m-%d')
                where_conditions.append("DATE(p.created_at) >= :start_date")
                params['start_date'] = start_date
            except ValueError:
                pass
                
        if end_date:
            try:
                datetime.strptime(end_date, '%Y-%m-%d')
                where_conditions.append("DATE(p.created_at) <= :end_date")
                params['end_date'] = end_date
            except ValueError:
                pass
        
        if search:
            where_conditions.append("(p.payment_no LIKE :search OR o.order_no LIKE :search)")
            params['search'] = f'%{search}%'
        
        where_clause = " WHERE " + " AND ".join(where_conditions) if where_conditions else ""
        
        # 查询总数
        count_sql = f"SELECT COUNT(*) as total FROM payments p LEFT JOIN orders o ON p.order_id = o.id {where_clause}"
        count_result = db.session.execute(db.text(count_sql), params).scalar()
        total = count_result if count_result else 0
        
        # 计算偏移量
        offset = (page - 1) * per_page
        
        # 查询支付记录列表
        list_sql = f"""
        SELECT 
            p.id, p.payment_no, p.amount, p.payment_method, p.status,
            p.paid_at, p.created_at, p.transaction_id,
            o.order_no, o.user_id, o.venue_id, o.activity_id,
            u.nickname as user_name,
            v.name as venue_name,
            a.title as activity_title
        FROM payments p
        LEFT JOIN orders o ON p.order_id = o.id
        LEFT JOIN users u ON o.user_id = u.id
        LEFT JOIN venues v ON o.venue_id = v.id
        LEFT JOIN activities a ON o.activity_id = a.id
        {where_clause}
        ORDER BY p.id DESC
        LIMIT :per_page OFFSET :offset
        """
        
        params['per_page'] = per_page
        params['offset'] = offset
        
        list_result = db.session.execute(db.text(list_sql), params)
        payments_data = []
        
        status_map = {0: '未支付', 1: '支付成功', 2: '支付失败', 3: '已退款'}
        
        for row in list_result:
            payments_data.append({
                'id': row.id,
                'payment_no': row.payment_no,
                'order_no': row.order_no,
                'activity_id': row.activity_id,
                'activity_title': row.activity_title,
                'amount': float(row.amount) if row.amount else 0,
                'payment_method': row.payment_method,
                'status': row.status,
                'status_text': status_map.get(row.status, '未知'),
                'transaction_id': row.transaction_id,
                'paid_at': str(row.paid_at) if row.paid_at else None,
                'created_at': str(row.created_at) if row.created_at else None,
                'user_name': row.user_name or '未知用户',
                'venue_name': row.venue_name or '未知场馆'
            })
        
        pages = (total + per_page - 1) // per_page
        
        return success_response({
            'total': total,
            'pages': pages,
            'page': page,
            'per_page': per_page,
            'payments': payments_data
        }, '获取支付记录成功')
        
    except Exception as e:
        current_app.logger.error(f"获取支付记录异常: {str(e)}")
        return error_response('服务器错误', 500)


@api_v1.route('/admin/payments/<int:payment_id>/logs', methods=['GET'])
@admin_required
@swag_from({
    "tags": ["支付管理"],
    "summary": "获取支付日志",
    "description": "获取指定支付记录的详细日志\n\n**🔐 需要管理员Token认证**",
    "security": [{"Bearer": []}],
    "parameters": [
        {"name": "payment_id", "in": "path", "type": "integer", "required": True, "description": "支付ID"}
    ],
    "responses": {
        "200": {"description": "获取成功"},
        "401": {"description": "未授权访问"},
        "404": {"description": "支付记录不存在"},
        "500": {"description": "服务器内部错误"}
    }
})
def get_payment_logs(payment_id):
    """获取支付日志"""
    try:
        from app.models.payment import Payment, PaymentLog
        
        # 查询支付记录
        payment = Payment.query.get(payment_id)
        if not payment:
            return error_response('支付记录不存在', 404)
        
        # 查询日志
        logs = PaymentLog.query.filter_by(payment_id=payment_id).order_by(PaymentLog.created_at.desc()).all()
        
        logs_data = [log.to_dict() for log in logs]
        
        return success_response({
            'payment': payment.to_dict(),
            'logs': logs_data
        }, '获取支付日志成功')
        
    except Exception as e:
        current_app.logger.error(f"获取支付日志异常: {str(e)}")
        return error_response('服务器错误', 500)
